package com.qipay.mapper;

import com.qipay.baas.model.Holiday;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Creator: Yao
 * Date:    2017/12/13
 * For:
 * Other:
 */
public class HolidaySqlProvider extends com.qipay.baas.mapper.HolidaySqlProvider {

    public String save(List<Holiday> list, String empty) {

        // check
        Assert.isTrue(CollectionUtils.isNotEmpty(list), "holiday list is empty");

        // init
        StringBuffer buffer = new StringBuffer("insert into holiday(`date`, `name`, `is_holiday`) ");
        int size = list.size();

        // fill
        for (int i = 0; i < size; i++) {

            Holiday p = list.get(i);
            if (null == p || StringUtils.isEmpty(p.getDate()))
                continue;

            if (0 != i)
                buffer.append(" union ");
            buffer.append(String.format(" select '%s', '%s', %s ", p.getDate(), p.getName(), p.getIsHoliday()));
        }

        return buffer.toString();
    }

    public String findLastByDate(Date date) {

        // check
        Assert.notNull(date, "date is null");

        // init
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return String.format("select * from holiday where date = '%04d-%02d-%02d' order by id desc limit 1",
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1,
                calendar.get(Calendar.DAY_OF_MONTH));
    }
}
